<template>
  <div class="pagination-container">
    <!-- Previous button -->
    <button
      @click="changePage(currentPage - 1)"
      :disabled="currentPage === 1"
      class="pagination-button prev-button"
      :class="{ 'disabled': currentPage === 1 }"
      aria-label="上一页"
    >
      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon">
        <polyline points="15 18 9 12 15 6"></polyline>
      </svg>
    </button>

    <!-- First page -->
    <button
      v-if="showFirstButton"
      @click="changePage(1)"
      class="pagination-button page-button"
      :class="{ 'active': currentPage === 1 }"
    >
      1
    </button>

    <!-- Left ellipsis -->
    <span v-if="showLeftEllipsis" class="ellipsis">...</span>

    <!-- Page numbers -->
    <button
      v-for="page in visiblePageNumbers"
      :key="page"
      @click="changePage(page)"
      class="pagination-button page-button"
      :class="{ 'active': currentPage === page }"
    >
      {{ page }}
    </button>

    <!-- Right ellipsis -->
    <span v-if="showRightEllipsis" class="ellipsis">...</span>

    <!-- Last page -->
    <button
      v-if="showLastButton"
      @click="changePage(totalPages)"
      class="pagination-button page-button"
      :class="{ 'active': currentPage === totalPages }"
    >
      {{ totalPages }}
    </button>

    <!-- Next button -->
    <button
      @click="changePage(currentPage + 1)"
      :disabled="currentPage === totalPages"
      class="pagination-button next-button"
      :class="{ 'disabled': currentPage === totalPages }"
      aria-label="下一页"
    >
      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon">
        <polyline points="9 18 15 12 9 6"></polyline>
      </svg>
    </button>

    <!-- Page info and jump to page -->
    <div class="pagination-info-container">
      <span class="pagination-info">{{ currentPage }} / {{ totalPages }} 页</span>

      <div class="pagination-jump">
        <span>跳至</span>
        <input
          type="number"
          v-model="jumpToPage"
          min="1"
          :max="totalPages"
          class="pagination-input"
          @keyup.enter="handleJumpToPage"
        />
        <span>页</span>
        <button
          @click="handleJumpToPage"
          class="pagination-button jump-button"
          aria-label="跳转到指定页"
        >
          跳转
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

const props = defineProps({
  totalItems: {
    type: Number,
    required: true
  },
  itemsPerPage: {
    type: Number,
    default: 10
  },
  maxVisiblePages: {
    type: Number,
    default: 5
  },
  initialPage: {
    type: Number,
    default: 1
  }
});

const emit = defineEmits(['page-change']);

const currentPage = ref(props.initialPage);
const jumpToPage = ref('');

// Calculate total pages
const totalPages = computed(() => {
  return Math.ceil(props.totalItems / props.itemsPerPage);
});

// Calculate visible page numbers
const visiblePageNumbers = computed(() => {
  if (totalPages.value <= props.maxVisiblePages) {
    // If total pages is less than max visible, show all pages
    return Array.from({ length: totalPages.value }, (_, i) => i + 1);
  }

  // Calculate start and end of visible pages
  let start = Math.max(currentPage.value - Math.floor(props.maxVisiblePages / 2), 1);
  let end = start + props.maxVisiblePages - 1;

  // Adjust if end exceeds total pages
  if (end > totalPages.value) {
    end = totalPages.value;
    start = Math.max(end - props.maxVisiblePages + 1, 1);
  }

  return Array.from({ length: end - start + 1 }, (_, i) => start + i);
});

// Determine if ellipsis and first/last buttons should be shown
const showLeftEllipsis = computed(() => {
  return visiblePageNumbers.value[0] > 1;
});

const showRightEllipsis = computed(() => {
  return visiblePageNumbers.value[visiblePageNumbers.value.length - 1] < totalPages.value;
});

const showFirstButton = computed(() => {
  return visiblePageNumbers.value[0] > 1;
});

const showLastButton = computed(() => {
  return visiblePageNumbers.value[visiblePageNumbers.value.length - 1] < totalPages.value;
});

// Change page function
const changePage = (page) => {
  if (page < 1 || page > totalPages.value || page === currentPage.value) {
    return;
  }

  currentPage.value = page;
  emit('page-change', {
    page: currentPage.value,
    offset: (currentPage.value - 1) * props.itemsPerPage,
    limit: props.itemsPerPage
  });
};

// Handle jump to page
const handleJumpToPage = () => {
  const pageNumber = parseInt(jumpToPage.value);

  if (!isNaN(pageNumber) && pageNumber >= 1 && pageNumber <= totalPages.value) {
    changePage(pageNumber);
  }

  // Clear the input after jumping
  jumpToPage.value = '';
};

// Watch for changes in totalItems or itemsPerPage
watch([() => props.totalItems, () => props.itemsPerPage], () => {
  // If current page is now invalid, reset to page 1
  if (currentPage.value > totalPages.value) {
    changePage(1);
  }
});
</script>

<style scoped>
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  margin: 1.5rem 0;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  flex-wrap: wrap;
}

.pagination-button {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 2.5rem;
  height: 2.5rem;
  padding: 0 0.75rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  transition: all 0.2s ease;
  cursor: pointer;
  border: 1px solid #e2e8f0;
  background-color: white;
  color: #4b5563;
}

.pagination-button:hover:not(.disabled):not(.active) {
  background-color: #f3f4f6;
  color: #1f2937;
}

.pagination-button.active {
  background-color: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.pagination-button.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.prev-button, .next-button {
  padding: 0;
  width: 2.5rem;
}

.icon {
  width: 1rem;
  height: 1rem;
}

.ellipsis {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  color: #6b7280;
}

.pagination-info-container {
  display: flex;
  align-items: center;
  margin-left: 1rem;
  gap: 1rem;
}

.pagination-info {
  color: #4b5563;
  font-size: 0.875rem;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #4b5563;
  font-size: 0.875rem;
}

.pagination-input {
  width: 3rem;
  height: 2.25rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.375rem;
  padding: 0 0.5rem;
  text-align: center;
  font-size: 0.875rem;
}

.jump-button {
  min-width: 3rem;
  height: 2.25rem;
  font-size: 0.75rem;
}

@media (max-width: 768px) {
  .pagination-container {
    flex-direction: column;
    gap: 1rem;
  }

  .pagination-info-container {
    margin-left: 0;
    width: 100%;
    justify-content: center;
  }
}

@media (max-width: 640px) {
  .pagination-button {
    min-width: 2rem;
    height: 2rem;
    padding: 0 0.5rem;
    font-size: 0.75rem;
  }

  .prev-button, .next-button {
    width: 2rem;
  }

  .icon {
    width: 0.875rem;
    height: 0.875rem;
  }

  .ellipsis {
    width: 1.5rem;
  }

  .pagination-info-container {
    flex-direction: column;
    gap: 0.5rem;
  }
}
</style>

<!-- 使用示例 -->
<!-- <Pagination
:totalItems="products.length"
:itemsPerPage="itemsPerPage"
:initialPage="1"
@page-change="handlePageChange"
/> -->
